package com.frank.framework.util;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnProperty(value = "spring.redis.enabled", havingValue = "true")
public class RedissonLockUtil {

    @Autowired
    private RedissonClient redissonClient;

    private static final String REDISSON_LOCK = "redissonlock:";

    // 默认过期时间30秒
    private static final Integer TIMEOUT = 30;
    /**
     * 对 key 加锁，
     * @ param key 键
     */
    public void lock(String key){
        String lockKey = REDISSON_LOCK + key;
        RLock lock = redissonClient.getLock(lockKey);
        // lock提供带timeout参数，timeout结束强制解锁，防止死锁
        lock.lock(TIMEOUT, TimeUnit.SECONDS);
    }
    /**
     * 对 key 加锁
     * @param key 键
     * @param leaseTime 过期时间
     * @param unit 单位
     */
    public void lock(String key, int leaseTime, TimeUnit unit ){
        String lockKey = REDISSON_LOCK + key;
        RLock lock = redissonClient.getLock(lockKey);
        // lock提供带timeout参数，timeout结束强制解锁，防止死锁
        lock.lock(leaseTime, unit);
    }
    /**
     * 对 key 释放锁
     * @param key 键
     */
    public void unlock(String key){
        String lockKey = REDISSON_LOCK + key;
        RLock lock = redissonClient.getLock(lockKey);
        //如果锁被当前线程持有，则释放
        if(lock.isHeldByCurrentThread()){
            lock.unlock();
        }
    }

    public Boolean isLocked(String key){
        String lockKey = REDISSON_LOCK + key;
        RLock lock = redissonClient.getLock(lockKey);
        boolean locked = lock.isLocked();
        return locked;
    }
}
